package com.danbay.framework.utils;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @author SJG
 *         2017/11/13.
 */
@Slf4j
public class BeanUtils extends org.apache.commons.beanutils.BeanUtils {


    /**
     * 将bean从类型T转换为类型R
     *
     * @param from    待转换的bean
     * @param toClass 目标bean类型
     * @param <T>     待转换的bean类型
     * @param <R>     目标bean类型
     * @return 目标bean
     */
    public static <T, R> R convert(T from, Class<R> toClass) {
        if(from!=null && from.getClass()==toClass){
            return (R) from;
        }

        try {
            R result = toClass.newInstance();
            copyProperties(result, from);
            return result;
        } catch (Exception e) {
            log.error("cover bean failed", e);
        }
        return null;
    }

    /**
     * 将List中的bean从类型T转换为类型R
     *
     * @param from    待转换的bean
     * @param toClass 目标bean类型
     * @param <T>     待转换的bean类型
     * @param <R>     目标bean类型
     * @return 目标bean
     */
    public static <T, R> List<R> convert(List<T> from, Class<R> toClass) {
        List<R> resultList = new ArrayList();
        try {
            for (T t : from) {
                R result = toClass.newInstance();
                copyProperties(result, t);
                resultList.add(result);
            }
            return resultList;
        } catch (Exception e) {
            log.error("convert list failed", e);
        }
        return null;
    }
}
